﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using DeviceMaintainGIS.Server.Common;

namespace DeviceMaintainGIS.Server
{



    public class ChatHub : Hub
    {
        public static List<MessageModel> MessageList = new List<MessageModel>();

        private readonly ChatTicker ticker;

        public ChatHub()
        {
            ticker = ChatTicker.Instance;
        }

        public void Send(string group, string username)
        {
            var config = new HubConfiguration();
            config.EnableDetailedErrors = true;
            config.EnableJavaScriptProxies = false;
            config.EnableJSONP = true;
            JavaScriptSerializer jsonSerialize = new JavaScriptSerializer();
            //String strJson = jsonSerialize.Serialize(item);//输出结果：{"Id":1,"UserName":"张三","Time":"\/Date(1297950721668)\/"}


            //注册到全局  
            ticker.GlobalContext.Groups.Add(Context.ConnectionId, group);
            //Clients.All.broadcastMessage(group, "用户注册:" + username);

            string pars = string.Format("发送广播信息：\r\n 时间 = {0};\r\n 参数 = {1};"
            , System.DateTime.Now
            , "用户ID：" + group + "注册到广播中！");
            LogHelper.WriteLog(typeof(ChatTicker), pars);
        }
    }

    public class ChatTicker
    {
        #region 实现一个单例

        private static readonly ChatTicker _instance = new ChatTicker(GlobalHost.ConnectionManager.GetHubContext<ChatHub>());

        private readonly IHubContext m_context;

        //public  ChatTicker(string tag, string data)
        //{
        //    new ChatTicker(GlobalHost.ConnectionManager.GetHubContext<ChatHub>(), tag, data);
        //    //ChatTicker ticker = Instance;
        //    //ticker.GlobalContext.Groups.Add(Context.ConnectionId, tag);
        //    //connection.hub.start().done
        //}
        private ChatTicker(IHubContext context)
        {
            m_context = context;
            //这里不能直接调用Sender，因为Sender是一个不退出的“死循环”，否则这个构造函数将不会退出。  
            //其他的流程也将不会再执行下去了。所以要采用异步的方式。  
            Task.Run(() => Sender());
        }

        public IHubContext GlobalContext
        {
            get { return m_context; }
        }

        public static ChatTicker Instance
        {
            get { return _instance; }
        }

        #endregion

        public void Sender()
        {
            JavaScriptSerializer jsonSerialize = new JavaScriptSerializer();

            while (true)
            {
                Thread.Sleep(1000);
                lock (ChatHub.MessageList)
                {
                    if (ChatHub.MessageList.Count > 0)
                    {
                        foreach (MessageModel item in ChatHub.MessageList)
                        {
                            m_context.Clients.Group(item.UserID).broadcastMessage("信息:" + item.Message);
                            String strJson = jsonSerialize.Serialize(item);//输出结果：{"Id":1,"UserName":"张三","Time":"\/Date(1297950721668)\/"}
                            string pars = string.Format("发送广播信息：\r\n 时间 = {0};\r\n 参数 = {1};"
                            , System.DateTime.Now
                            , strJson);
                            LogHelper.WriteLog(typeof(ChatTicker), pars);
                        }
                    }
                    else
                    {
                        m_context.Clients.All.broadcastMessage("提示", "消息数组为空");
                    }
                }
            }
        }
    }

    /// <summary>
    /// 存储信息
    /// </summary>
    public class MessageModel
    {
        /// <summary>
        /// 用户名
        /// </summary>
        public string UserID { get; set; }
        /// <summary>
        /// 发送信息
        /// </summary>
        public string Message { get; set; }
    }
}